package com.zb.service.impl;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zb.bean.Permission;
import com.zb.dao.PermissionDao;
import com.zb.qo.PermissionQo;
import com.zb.service.PermissionService;
import com.zb.vo.PageVo;
import com.zb.vo.PermissionVo;
import com.zb.vo.ZtreeVo;

/**
 * 权限 操作Service
 * 
 * 作者: zhoubang 日期：2015年3月26日 下午2:11:50
 */
@Service(value = "permissionServiceImpl")
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public List<Permission> getUserPermissions(String userName)
            throws Exception {
        return permissionDao.getUserPermissions(userName);
    }

    @Override
    public PageVo<PermissionVo> getPermissionList(PermissionQo permissionQo) throws Exception {
        return permissionDao.getPermissionList(permissionQo);
    }

    @Override
    public List<ZtreeVo> queryAllFormatWithZtree(boolean isModify) throws Exception {
        List<ZtreeVo> results = new ArrayList<ZtreeVo>();
        if(!isModify){
            ZtreeVo result = new ZtreeVo();
            result.setId("-1");
            result.setpId("0");
            result.setName("无上级权限");
            results.add(result);
        }
        List<Permission> permissions = permissionDao.queryAll();
        if (CollectionUtils.isNotEmpty(permissions)) {
            for (Permission pms : permissions) {
                ZtreeVo foo = new ZtreeVo();
                foo.setId(pms.getId());
                foo.setpId(pms.getParentId());
                foo.setName(pms.getName() + " - " + pms.getCode());
                results.add(foo);
            }
        }
        return results;
    }

    @Override
    public void addPermission(Permission permission) throws Exception {
        permission.setName(URLDecoder.decode(permission.getName(), "UTF-8"));
        permission.setCode(URLDecoder.decode(permission.getCode(), "UTF-8"));
        permissionDao.save(permission);
    }

    @Override
    public void delPermission(Permission permission) throws Exception {
        permissionDao.delete(permission);
    }

    @Override
    public List<Permission> getPermissionByPid(String pid) throws Exception {
        return permissionDao.query("parentId", pid);
    }

    @Override
    public boolean checkCodeIsExists(Permission permission) throws Exception {
        List<Permission> listByCode = permissionDao.query("code", URLDecoder.decode(permission.getCode(), "UTF-8"));
        if(listByCode != null && listByCode.size() > 0){
            return true;
        }
        return false;
    }

}
